// pages/fill/fill.js
var cardName = require("../untils/cardName.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cardNumber: '', //卡号

    branch: '', //支行信息

    name: '', //开户人姓名

    phone: '', //手机号z

    prompt: '', //密码提示

    note: '', //添加备注

    day: '', //还款日

    bankIcon: "", // 银行icon

    cardName: "", // 卡名称

    number: "",
    items: "",

    // 从支付宝拉去的银行信息
    /*bank: "ICBC"
      cardType: "DC"
      key: "6212261202027041590"
      messages: []
      stat: "ok"
      validated: true*/
    cardInfo: {},

    cardType: 'DC',

    item: {},
    id: ''

  },

  // 卡号
  onNumber: function (e) {
    var number = e.detail.value;
    var formateNumber = number.replace(/(\d{4})(?=\d)/g, "$1 "); //replace(/\s/g,'');
    this.setData({
      number: formateNumber
    });


    this.getCardInfo(formateNumber);


  },

  // 卡号失去焦点时
  onCardNumberEndInput: function (e) {
    this.getCardInfo(e.detail.value);
  },

  // 选择银行
  onSelectBankTap: function () {
    wx.navigateTo({
      url: '../backname/backname'
    })
  },
  onListen: function (e) {

  },

  onBranch: function (e) {

    this.data.branch = e.detail.value
  }, //支行信息提取

  onName: function (e) {

    this.data.name = e.detail.value
  }, //开户人姓名提取

  onPhone: function (e) {
    this.data.phone = e.detail.value
  }, //手机号信息提取 

  onPrompt: function (e) {
    this.data.prompt = e.detail.value
  }, //密码提示信息提取

  onNote: function (e) {
    this.data.note = e.detail.value
  }, //备注信息提取

  onDay: function (e) {
    this.data.day = e.detail.value
  }, //信用卡还款日期信息提取

  // 获取银行卡信息
  getCardInfo: function (cardCode) {

    cardCode = cardCode.replace(/\s/g, "");

    let that = this;
    wx.request({
      url: "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + cardCode + "&cardBinCheck=true",
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        // debugger，获取银行名称     
        that.data.cardType = res.data.cardType
        if (res.data.bank) {

          that.updateCardInfo(res.data.bank);
        }
      }
    });
  },

  // 更新卡片信息
  updateCardInfo: function (cardCode) {

    let bankIcon = "../../images/bank_log/" + cardCode + ".jpg";

    let cardInfo = {
      code: cardCode,
      name: cardName.getCardName(cardCode)
    }

    this.setData({
      cardInfo: cardInfo,
      bankIcon: bankIcon,
      cardName: cardName.getCardName(cardCode)
    });

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onLoad: function (options) {

    this.data.id = options.id;
    const db = wx.cloud.database()
    let that = this;
    db.collection('card').where({
      _id: this.data.id // 填入当前用户 openid
    }).get({
      success: function (res) {

        if (res.data.length > 0) {
          that.setData({

            name: res.data[0].name,
            number: res.data[0].number,
            branch: res.data[0].branch,
            day: res.data[0].day,
            phone: res.data[0].phone,
            prompt: res.data[0].prompt,
            note: res.data[0].note,
            cardCode: res.data[0].cardCode,
            cardName: res.data[0].cardName,
            bankIcon: `../../images/bank_log/${res.data[0].cardCode}.jpg`,
          })
        }
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onSave: function (e) {

    if (this.data.number < 16) {
      wx.showToast({
        title: "请输入正确的卡号",
        icon: "none"
      });
      return;
    }

    //判断是否输入正确的卡号
    if (this.data.name.length === 0) {


      wx.showToast({
        title: '请输入开户人姓名',
        icon: 'none'
      })
      return;
    }


    let that = this;
    let data = {
      number: that.data.number,
      branch: that.data.branch,
      name: that.data.name,
      phone: that.data.phone,
      prompt: that.data.prompt,
      note: that.data.note,
      day: that.data.day,
      cardCode: that.data.cardInfo.code,
      cardName: that.data.cardInfo.name
    }

    //把图片存到users集合表
    const db = wx.cloud.database();
    db.collection('card')
      .doc(this.data.id)
      .update({
        // data 字段表示需新增的 JSON 数据
        data: data,
        success: function (res) {
          wx.showToast({
            title: "卡片修改成功",
            icon: "none"
          });
        },
        fail: console.error
      })

    setTimeout(() => {
      wx.navigateBack({
        delta: 1,
      })
    }, 900);

  },



  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
});